<template>
  <div class="app-container home" :class="{ mobile: appStore.device === 'mobile' } ">
    <!-- 游客角色：显示报名信息页面 -->
    <div v-if="isGuest && hasValidEnrollTime" class="guest-enroll-page">
      <h1 class="enroll-title">{{ currentEnrollInfo.title || `${currentEnrollInfo.yearNum}年工程硕博士项目报名` }}</h1>
      <div class="enroll-time">
        报名时间: {{ formatEnrollTime(currentEnrollInfo.startTime) }}至{{ formatEnrollTime(currentEnrollInfo.endTime) }}
      </div>
      <el-button
        type="primary"
        class="enroll-button"
        @click="handleEnroll"
        :disabled="!canEnroll"
      >
        立即报名
      </el-button>
    </div>

    <!-- 非游客角色：显示原有内容 -->
    <template v-else>
      <!-- 欢迎信息 -->
      <h1 class="welcome-title">
        {{ userInfo.nickName || userInfo.userName || 'XX' }}，您好！欢迎来到工程硕博士项目管理系统。
      </h1>

      <!-- 按钮区域 -->
      <div class="button-group">
      <div
        v-for="item in buttonList"
        :key="item.type"
        class="button-item"
        :class="{ active: activeTab === item.type }"
        @click="handleTabChange(item.type)"
      >
        <el-badge :value="item.count" :hidden="item.count === 0" class="button-badge">
          <div class="button-icon" :style="{ backgroundColor: item.color }">
            <el-icon v-if="item.icon" :size="24">
              <component :is="item.icon" />
            </el-icon>
          </div>
        </el-badge>
        <div class="button-label">{{ item.label }}</div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Refresh"
            @click="handleGetList"
          >
            刷新
          </el-button>
        </el-col>
      </el-row>

      <!-- 我的待办表格 -->
      <el-table
        v-if="activeTab === 'todo'"
        v-loading="loading"
        :data="todoList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="待办事项"
          align="center"
          prop="progressType"
          :show-overflow-tooltip="true"
          min-width="250"
        >
          <template #default="scope">
            您有一条 《{{ getProgressTypeText(scope.row.progressType) }}》 待办
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          prop="progressStatus"
          width="120"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.progressStatus)">
              {{ getStatusText(scope.row.progressStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleTodoAction(scope.row)"
              :loading="readLoading"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 我的待审表格 -->
      <el-table
        v-if="activeTab === 'approval'"
        v-loading="loading"
        :data="approvalList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="申请类型"
          align="center"
          prop="approvalInfo.approvalType"
          :show-overflow-tooltip="true"
          min-width="150"
        >
          <template #default="scope">
            {{ getApprovalTypeText(scope.row.approvalInfo?.approvalType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="申请人"
          align="center"
          prop="approvalInfo.createBy"
          width="120"
        />
        <el-table-column
          label="申请时间"
          align="center"
          prop="approvalInfo.createTime"
          width="180"
        />
        <el-table-column
          label="审批状态"
          align="center"
          prop="approvalStatus"
          width="120"
        >
          <template #default="scope">
            <el-tag :type="getApprovalStatusType(scope.row.approvalInfo?.approvalStatus)">
              {{ getApprovalStatusText(scope.row.approvalInfo?.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleApprovalView(scope.row)"
            >
              审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 我的申请表格 -->
      <el-table
        v-if="activeTab === 'submitted'"
        v-loading="loading"
        :data="submittedList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="申请类型"
          align="center"
          prop="approvalInfo.approvalType"
          :show-overflow-tooltip="true"
          min-width="150"
        >
          <template #default="scope">
            {{ getApprovalTypeText(scope.row.approvalInfo?.approvalType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="当前状态"
          align="center"
          prop="approvalStatus"
          width="120"
        >
          <template #default="scope">
            <el-tag :type="getApprovalStatusType(scope.row.approvalInfo?.approvalStatus)">
              {{ getApprovalStatusText(scope.row.approvalInfo?.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="提交时间"
          align="center"
          prop="approvalInfo.createTime"
          width="180"
        />
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleSubmittedView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 我的已办表格 -->
      <el-table
        v-if="activeTab === 'approved'"
        v-loading="loading"
        :data="approvedList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="申请类型"
          align="center"
          prop="approvalInfo.approvalType"
          :show-overflow-tooltip="true"
          min-width="150"
        >
          <template #default="scope">
            {{ getApprovalTypeText(scope.row.approvalInfo?.approvalType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="申请人"
          align="center"
          prop="approvalInfo.createBy"
          width="120"
        />
        <el-table-column
          label="申请时间"
          align="center"
          prop="approvalInfo.createTime"
          width="180"
        />
        <el-table-column
          label="审批状态"
          align="center"
          prop="approvalStatus"
          width="120"
        >
          <template #default="scope">
            <el-tag :type="getApprovalStatusType(scope.row.approvalInfo?.approvalStatus)">
              {{ getApprovalStatusText(scope.row.approvalInfo?.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleApprovedView(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 草稿箱表格 -->
      <el-table
        v-if="activeTab === 'draft'"
        v-loading="loading"
        :data="draftList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="草稿名称"
          align="center"
          prop="name"
          :show-overflow-tooltip="true"
          min-width="250"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        />
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleDraftAction(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 其他消息表格 -->
      <el-table
        v-if="activeTab === 'other'"
        v-loading="loading"
        :data="otherList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="消息内容"
          align="center"
          prop="content"
          :show-overflow-tooltip="true"
          min-width="250"
        />
        <el-table-column
          label="时间"
          align="center"
          prop="createTime"
          width="180"
        />
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleOtherAction(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 报名时间表格 -->
      <el-table
        v-if="activeTab === 'signTime'"
        v-loading="loading"
        :data="signTimeList"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        />
        <el-table-column
          label="标题"
          align="center"
          prop="title"
          :show-overflow-tooltip="true"
          min-width="200"
        />
        <el-table-column
          label="年份"
          align="center"
          prop="yearNum"
          width="100"
        />
        <el-table-column
          label="开始时间"
          align="center"
          prop="startTime"
          width="180"
        />
        <el-table-column
          label="结束时间"
          align="center"
          prop="endTime"
          width="180"
        />
        <el-table-column
          label="状态"
          align="center"
          prop="status"
          width="100"
        >
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enable' ? 'success' : 'info'">
              {{ scope.row.status === 'enable' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          :show-overflow-tooltip="true"
          min-width="200"
        />
        <el-table-column
          label="附件"
          align="center"
          prop="fileObjects"
          width="200"
        >
          <template #default="scope">
            <div v-if="scope.row.fileObjects && scope.row.fileObjects.length > 0" class="file-list">
              <el-link
                v-for="(file, index) in scope.row.fileObjects"
                :key="index"
                :underline="false"
                @click="handleFileDownload(file)"
                type="primary"
                style="margin-right: 8px; display: inline-block;"
              >
                <el-icon><Document /></el-icon>
                {{ file.fileName || file.name || getFileNameFromPath(file.filePath || file.url || file) }}
              </el-link>
            </div>
            <span v-else>无</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleGetList"
      />
    </div>
    </template>
  </div>
</template>

<script setup name="Index">
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { Document, Plus, Check, Folder, Message, Clock } from '@element-plus/icons-vue'
import {
  getList,
  changeState,
  getMyApprovalList,
  getMyApprovedList,
  getMyApprovalCount,
  getMySubmittedList,
} from '@/api/my-todo'
import { getList as getSignTimeList, getValidEnrollTime } from '@/api/sign-time'
import { downloadFile, getFileNameFromPath } from '@/utils/fileDownload'
import useUserStore from '@/store/modules/user'
import useAppStore from '@/store/modules/app'
import { approvalStatusMap, approvalStatusTypeMap, approvalTypeMap } from '@/utils/constant'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()
// 用户信息
const userInfo = ref({})

// 判断是否为游客角色
const isGuest = computed(() => {
  const roles = userStore.roles || []
  return roles.includes('guest') || roles.includes('ROLE_GUEST') || roles.includes('student')
})

// 当前报名信息
const currentEnrollInfo = ref({
  title: '',
  yearNum: '',
  startTime: '',
  endTime: '',
  status: ''
})

// 是否可以报名
const canEnroll = computed(() => {
  if (!currentEnrollInfo.value.startTime || !currentEnrollInfo.value.endTime) {
    return false
  }
  const now = new Date()
  const startTime = new Date(currentEnrollInfo.value.startTime)
  const endTime = new Date(currentEnrollInfo.value.endTime)
  return now >= startTime && now <= endTime && currentEnrollInfo.value.status === 'enable'
})

// 格式化报名时间
const formatEnrollTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}年${month}月${day}日 ${hours}:${minutes}`
}

// 是否有有效的报名时间
const hasValidEnrollTime = computed(() => {
  return !!(currentEnrollInfo.value && currentEnrollInfo.value.yearNum)
})

// 立即报名
const handleEnroll = () => {
  router.push({
    path: '/sign-list/edit/add',
    query: {
      mode: 'add'
    }
  })
}

// 当前激活的标签
const activeTab = ref('todo')

// 所有按钮列表
const allButtonList = [
  {
    type: 'todo',
    label: '我的待办',
    color: '#409EFF',
    icon: Document,
    count: 0,
  },
  {
    type: 'approval',
    label: '我的待审',
    color: '#E6A23C',
    icon: Plus,
    count: 0,
  },
  {
    type: 'submitted',
    label: '我的申请',
    color: '#36CBCB',
    icon: Plus,
    count: 0,
  },
  {
    type: 'approved',
    label: '我的已办',
    color: '#67C23A',
    icon: Check,
    count: 0,
  },
  {
    type: 'draft',
    label: '草稿箱',
    color: '#9C27B0',
    icon: Folder,
    count: 0,
  },
  {
    type: 'other',
    label: '其他消息',
    color: '#F56C6C',
    icon: Message,
    count: 0,
  },
  {
    type: 'signTime',
    label: '报名时间',
    color: '#909399',
    icon: Clock,
    count: 0,
  },
]

// 按钮列表（根据角色过滤）
const buttonList = ref([])

// 列表数据
const todoList = ref([])
const approvalList = ref([])
const submittedList = ref([])
const approvedList = ref([])
const draftList = ref([])
const otherList = ref([])
const signTimeList = ref([])

// 加载状态
const loading = ref(false)
const readLoading = ref(false)

// 总数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 代办类型映射（复用审批类型映射）
const progressTypeMap = approvalTypeMap

// 状态映射
const statusMap = {
  unread: '未读',
  read: '已读',
  processed: '已处理',
  refuse: '拒绝',
}

// 状态类型映射
const statusTypeMap = {
  unread: 'info',
  read: 'warning',
  processed: 'success',
  refuse: 'danger',
}

// 获取代办类型文本
const getProgressTypeText = (type) => {
  return progressTypeMap[type] || type
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  return statusTypeMap[status] || 'info'
}

// 获取审批类型文本
const getApprovalTypeText = (type) => {
  return approvalTypeMap[type] || type
}

// 获取审批状态文本
const getApprovalStatusText = (status) => {
  return approvalStatusMap[status] || status
}

// 获取审批状态标签类型
const getApprovalStatusType = (status) => {
  return approvalStatusTypeMap[status] || 'info'
}

// 切换标签
const handleTabChange = (type) => {
  activeTab.value = type
  queryParams.pageNum = 1
  handleGetList()
}

// 获取列表数据
const handleGetList = () => {
  loading.value = true

  switch (activeTab.value) {
    case 'todo':
      getTodoList()
      break
    case 'approval':
      getApprovalList()
      break
    case 'submitted':
      getSubmittedList()
      break
    case 'approved':
      getApprovedList()
      break
    case 'draft':
      getDraftList()
      break
    case 'other':
      getOtherList()
      break
    case 'signTime':
      getSignTimeListData()
      break
    default:
      loading.value = false
      break
  }
}

// 获取待办列表
const getTodoList = () => {
  getList(queryParams)
    .then((res) => {
      loading.value = false
      todoList.value = res.rows || []
      total.value = res.total || 0
    })
    .catch(() => {
      loading.value = false
    })
}

// 获取我的待审列表
const getApprovalList = () => {
  getMyApprovalList({ ...queryParams, userId: userStore.id })
    .then((res) => {
      loading.value = false
      approvalList.value = res?.rows || []
      total.value = res?.total || 0
    })
    .catch(() => {
      loading.value = false
    })
}

// 获取我的申请列表
const getSubmittedList = () => {
  getMySubmittedList({ ...queryParams, userId: userStore.id })
    .then((res) => {
      loading.value = false
      submittedList.value = res?.rows || []
      total.value = res?.total || 0
    })
    .catch(() => {
      loading.value = false
    })
}

// 获取我的已办列表
const getApprovedList = () => {
  getMyApprovedList({ ...queryParams, userId: userStore.id })
    .then((res) => {
      loading.value = false
      console.log(res, 'approvedList')
      approvedList.value = res?.rows || []
      total.value = res?.total || 0
    })
    .catch(() => {
      loading.value = false
    })
}

// 获取草稿箱列表（占位）
const getDraftList = () => {
  setTimeout(() => {
    loading.value = false
    draftList.value = []
    total.value = 0
  }, 300)
}

// 获取其他消息列表（占位）
const getOtherList = () => {
  setTimeout(() => {
    loading.value = false
    otherList.value = []
    total.value = 0
  }, 300)
}

// 获取有效的报名时间（游客使用）
const getValidEnrollTimeData = () => {
  loading.value = true
  getValidEnrollTime()
    .then((res) => {
      loading.value = false
      if (res.data) {
        currentEnrollInfo.value = {
          title: res.data.title || `${res.data.yearNum}年工程硕博士项目报名`,
          yearNum: res.data.yearNum,
          startTime: res.data.startTime,
          endTime: res.data.endTime,
          status: res.data.status
        }
      } else {
        currentEnrollInfo.value = {
          title: '',
          yearNum: '',
          startTime: '',
          endTime: '',
          status: ''
        }
      }
    })
    .catch(() => {
      loading.value = false
      currentEnrollInfo.value = {
        title: '',
        yearNum: '',
        startTime: '',
        endTime: '',
        status: ''
      }
    })
}

// 获取报名时间列表
const getSignTimeListData = () => {
  getSignTimeList(queryParams)
    .then((res) => {
      loading.value = false
      signTimeList.value = res.rows || []
      total.value = res.total || 0
    })
    .catch(() => {
      loading.value = false
      signTimeList.value = []
      total.value = 0
    })
}

// 下载附件
const handleFileDownload = (file) => {
  downloadFile(file)
}

// 根据角色过滤按钮列表
const filterButtonListByRole = () => {
  const roles = userStore.roles || []
  const isGuest = roles.includes('guest') || roles.includes('ROLE_GUEST')
  
  if (isGuest) {
    // 游客角色：仅展示报名时间
    buttonList.value = allButtonList.filter(item => item.type === 'signTime')
    // 如果是游客，默认激活报名时间标签
    if (activeTab.value !== 'signTime') {
      activeTab.value = 'signTime'
    }
  } else {
    // 其他角色：不展示报名时间
    buttonList.value = allButtonList.filter(item => item.type !== 'signTime')
    // 如果当前激活的是报名时间，切换到第一个标签
    if (activeTab.value === 'signTime') {
      activeTab.value = buttonList.value[0]?.type || 'todo'
    }
  }
}

// 处理待办操作
const handleTodoAction = debounce(
  (row) => {
    readLoading.value = true
    changeState({
      id: row.id,
      progressStatus: 'read',
    })
      .then(() => {
        ElMessage.success('已标记为已读')
        handleGetList()
        fetchCounts()

        switch (row.progressType) {
          case 'student_infor_flow':
            router.push({
              path: `/student-list/edit/${row.businessId}`,
              query: {
                type: 'edit',
              },
            })
            break
          case 'student_ent_teacher_flow_1':
          case 'student_ent_teacher_flow':
            router.push({
              path: '/corporate-mentor/edit',
              query: {
                mode: 'edit',
                id: row.businessId,
              },
            })
            break
          case 'student_school_teacher_flow':
            router.push({
              path: `/university-mentor/edit/${row.businessId}`,
              query: {
                mode: 'edit',
                id: row.businessId,
              },
            })
            break
          case 'ent_join_manage_flow':
            router.push({
              path: `/enterprise-practice-manage/edit/${row.businessId}`,
              query: {
                mode: 'edit',
              },
            })
            break
          case 'ent_plan_flow':
            router.push({
              path: `/enterprise-practice-program/edit/${row.businessId}`,
              query: {
                mode: 'edit',
              },
            })
            break
          case 'ent_progress_flow':
            router.push({
              path: `/enterprise-practice-progress/edit/${row.businessId}`,
              query: {
                mode: 'edit',
              },
            })
            break
          case 'enroll_flow':
            router.push({
              path: `/sign-list/edit/${row.businessId}`,
              query: {
                mode: 'edit',
              },
            })
            break
          default:
            ElMessage.warning('暂不支持该类型的待办处理')
            break
        }
      })
      .catch(() => {})
      .finally(() => {
        readLoading.value = false
      })
  },
  500,
  {
    leading: true,
    trailing: false,
  }
)

// 查看我的待审
const handleApprovalView = (row) => {
  const approvalType = row.approvalInfo?.approvalType
  const businessId = row.approvalInfo?.businessId

  if (!approvalType || !businessId) {
    ElMessage.error('无法获取审批信息')
    return
  }

  switch (approvalType) {
    case 'student_infor_flow':
      router.push({
        path: `/student-list/edit/${businessId}`,
        query: {
          type: 'approve',
        },
      })
      break
    case 'student_ent_teacher_flow_1':
    case 'student_ent_teacher_flow':
      router.push({
        path: '/corporate-mentor/edit',
        query: {
          mode: 'approve',
          id: businessId,
        },
      })
      break
    case 'student_school_teacher_flow':
      router.push({
        path: `/university-mentor/edit/${businessId}`,
        query: {
          mode: 'approve',
          id: businessId,
        },
      })
      break
    case 'ent_join_manage_flow':
      router.push({
        path: `/enterprise-practice-manage/edit/${businessId}`,
        query: {
          mode: 'approve',
        },
      })
      break
    case 'ent_plan_flow':
      router.push({
        path: `/enterprise-practice-program/edit/${businessId}`,
        query: {
          mode: 'approve',
        },
      })
      break
    case 'ent_progress_flow':
      router.push({
        path: `/enterprise-practice-progress/edit/${businessId}`,
        query: {
          mode: 'approve',
        },
      })
      break
    case 'enroll_flow':
      router.push({
        path: `/sign-list/edit/${businessId}`,
        query: {
          mode: 'approve',
        },
      })
      break
    default:
      ElMessage.error('不支持的审批类型')
      break
  }
}

// 查看我的申请
const handleSubmittedView = (row) => {
  const approvalType = row.approvalInfo?.approvalType
  const businessId = row.approvalInfo?.businessId

  if (!approvalType || !businessId) {
    ElMessage.error('无法获取审批信息')
    return
  }

  switch (approvalType) {
    case 'student_infor_flow':
      router.push({
        path: `/student-list/edit/${businessId}`,
        query: {
          type: 'view',
        },
      })
      break
    case 'student_ent_teacher_flow_1':
    case 'student_ent_teacher_flow':
      router.push({
        path: '/corporate-mentor/edit',
        query: {
          mode: 'detail',
          id: businessId,
        },
      })
      break
    case 'student_school_teacher_flow':
      router.push({
        path: `/university-mentor/edit/${businessId}`,
        query: {
          mode: 'detail',
          id: businessId,
        },
      })
      break
    case 'ent_join_manage_flow':
      router.push({
        path: `/enterprise-practice-manage/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'ent_plan_flow':
      router.push({
        path: `/enterprise-practice-program/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'ent_progress_flow':
      router.push({
        path: `/enterprise-practice-progress/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'enroll_flow':
      router.push({
        path: `/sign-list/edit/${businessId}`,
        query: {
          mode: 'detail',
        },
      })
      break
    default:
      ElMessage.error('不支持的审批类型')
      break
  }
}

// 查看我的已办
const handleApprovedView = (row) => {
  const approvalType = row.approvalInfo?.approvalType
  const businessId = row.approvalInfo?.businessId

  if (!approvalType || !businessId) {
    ElMessage.error('无法获取审批信息')
    return
  }

  switch (approvalType) {
    case 'student_infor_flow':
      router.push({
        path: `/student-list/edit/${businessId}`,
        query: {
          type: 'view',
        },
      })
      break
    case 'student_ent_teacher_flow_1':
    case 'student_ent_teacher_flow':
      router.push({
        path: '/corporate-mentor/edit',
        query: {
          mode: 'detail',
          id: businessId,
        },
      })
      break
    case 'student_school_teacher_flow':
      router.push({
        path: `/university-mentor/edit/${businessId}`,
        query: {
          mode: 'detail',
          id: businessId,
        },
      })
      break
    case 'ent_join_manage_flow':
      router.push({
        path: `/enterprise-practice-manage/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'ent_plan_flow':
      router.push({
        path: `/enterprise-practice-program/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'ent_progress_flow':
      router.push({
        path: `/enterprise-practice-progress/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    case 'enroll_flow':
      router.push({
        path: `/sign-list/edit/${businessId}`,
        query: {
          mode: 'view',
        },
      })
      break
    default:
      ElMessage.error('不支持的审批类型')
      break
  }
}

// 处理草稿箱操作（占位）
const handleDraftAction = (row) => {
  ElMessage.info('草稿箱功能待开发')
}

// 处理其他消息操作（占位）
const handleOtherAction = (row) => {
  ElMessage.info('其他消息功能待开发')
}

// 获取计数数据
const fetchCounts = async () => {
  const roles = userStore.roles || []
  const isGuest = roles.includes('guest') || roles.includes('ROLE_GUEST')
  
  // 游客角色不需要获取其他计数
  if (isGuest) {
    return
  }
  
  try {
    // 获取我的待办数量
    const todoRes = await getList({
      userId: userInfo.value.userId,
      pageNum: 1,
      pageSize: 1,
    })
    const todoButton = buttonList.value.find((item) => item.type === 'todo')
    if (todoButton) {
      todoButton.count = todoRes.total || 0
    }

    // 获取我的审批数量
    const approvalRes = await getMyApprovalCount({
      userId: userInfo.value.userId,
    })
    if (approvalRes && approvalRes.data) {
      const approvalButton = buttonList.value.find(
        (item) => item.type === 'approval'
      )
      const submittedButton = buttonList.value.find(
        (item) => item.type === 'submitted'
      )
      const approvedButton = buttonList.value.find(
        (item) => item.type === 'approved'
      )
      if (approvalButton) {
        approvalButton.count = approvalRes.data.pendingCount || 0
      }
      if (submittedButton) {
        submittedButton.count = approvalRes.data.submittedCount || 0
      }
      if (approvedButton) {
        approvedButton.count = approvalRes.data.approvedCount || 0
      }
    }
  } catch (error) {
    console.error('获取计数失败:', error)
  }
}

// 初始化
onMounted(() => {
  userStore.getInfo().then((res) => {
    userInfo.value = res.user
    // 根据角色过滤按钮列表
    filterButtonListByRole()
    
    // 如果是游客，获取有效的报名时间信息
    if (isGuest.value) {
      getValidEnrollTimeData()
    } else {
      fetchCounts()
      handleGetList()
    }
  })
})
</script>

<style lang="scss" scoped>
.home {
  padding: 20px;

  .welcome-title {
    font-size: 24px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 30px;
    text-align: center;
  }

  .button-group {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 30px;
    margin-bottom: 30px;
    flex-wrap: wrap;

    .button-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s;

      &.active {
        .button-icon {
          transform: scale(1.1);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .button-label {
          color: #409eff;
          font-weight: 600;
        }
      }

      .button-badge {
        margin-bottom: 8px;
      }

      .button-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        transition: all 0.3s;
      }

      .button-label {
        font-size: 14px;
        color: #606266;
        margin-top: 8px;
        transition: color 0.3s;
      }

      &:hover {
        .button-icon {
          transform: scale(1.05);
        }
      }
    }
  }

  .table-container {
    .mb8 {
      margin-bottom: 16px;
    }
  }
}

.mobile {
  .button-group {
    gap: 16px !important;
  }
  .button-icon {
    width: 52px !important;
    height: 52px !important;
  }
}

.guest-enroll-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40px 20px;

  .enroll-title {
    font-size: 32px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 40px;
    text-align: center;
  }

  .enroll-time {
    font-size: 18px;
    color: #f56c6c;
    margin-bottom: 40px;
    text-align: center;
    font-weight: 500;
  }

  .enroll-button {
    width: 200px;
    height: 50px;
    font-size: 18px;
    border: 2px solid #409EFF;
    color: #409EFF;
    background-color: #fff;
    border-radius: 4px;
    
    &:hover:not(:disabled) {
      background-color: #ecf5ff;
      border-color: #409EFF;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
      border-color: #dcdfe6;
      color: #c0c4cc;
    }
  }
}
</style>
